leetcodeJS

Personal solution for leetcode problem using Javascript

View on GitHub

Problem

The product difference between two pairs (a, b) and (c, d) is defined as (a _ b) - (c _ d).

For example, the product difference between (5, 6) and (2, 7) is (5 _ 6) - (2 _ 7) = 16.

Given an integer array nums, choose four distinct indices w, x, y, and z such that the product difference between pairs (nums[w], nums[x]) and (nums[y], nums[z]) is maximized.

Return the maximum such product difference.

Example 1:

Input: nums = [5,6,2,7,4] Output: 34 Explanation: We can choose indices 1 and 3 for the first pair (6, 7) and indices 2 and 4 for the second pair (2, 4). The product difference is (6 _ 7) - (2 _ 4) = 34.

Example 2:

Input: nums = [4,2,5,9,7,4,8] Output: 64 Explanation: We can choose indices 3 and 6 for the first pair (9, 8) and indices 1 and 5 for the second pair (2, 4). The product difference is (9 _ 8) - (2 _ 4) = 64.

Constraints:

4 <= nums.length <= 104 1 <= nums[i] <= 104

Pre analysis

We can sort the array and then take the difference of the first two and last two elements. To maximum first pair should be highest number and second pair should be lowest number. There is also a possibility of negative numbers, so we need to take care of that as well. But the constraint has 1 <= nums[i] <= 104, so we can safely ignore that.